﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Collections;
using PMisuseAn.io;
using PMisuseAn.util;

namespace PMisuseAn.behaviour.model
{
    class NextAggregationSatisfactionTest
    {
        public Dictionary<Dictionary<Dictionary<Dictionary<Dictionary<Attribute, Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool>>, string>, string>, string>, bool> processedAggregationStatements =
            new Dictionary<Dictionary<Dictionary<Dictionary<Dictionary<Attribute, Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool>>, string>, string>, string>, bool>();

        public void satisfiedAnalysis(Agent sendAgent, Agent receiveAgent, Agent subjectAgent,
                                    ListDictionary tokenisedAggregationThenContent, ListDictionary tokenisedContent, string aggregationStatement,
            List<Object> parameterisedContextInstances, Dictionary<Dictionary<Agent, Agent>, ListDictionary> sendReceiveContextAgent, Context contextInstance)
        {
            ListDictionary aggExtracts = extractAttributeAndJoinsFromStatement(tokenisedAggregationThenContent, contextInstance);

            Dictionary<Dictionary<Dictionary<Dictionary<Attribute, Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool>>, string>, string>, string> processedAggStatement =
                new Dictionary<Dictionary<Dictionary<Dictionary<Attribute, Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool>>, string>, string>, string>();

            bool lastGlobalEvaluation = false;
            bool globalTriggerBreak = false;

            foreach (DictionaryEntry extract in aggExtracts)
            {
                ListDictionary premise = (ListDictionary)extract.Key;
                ListDictionary conclusionList = (ListDictionary)extract.Value;

                Dictionary<Dictionary<Dictionary<Attribute, Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool>>, string>, string> MTGlobalJoins =
                    new Dictionary<Dictionary<Dictionary<Attribute, Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool>>, string>, string>();

                foreach (DictionaryEntry concItem in conclusionList)
                {
                    ListDictionary conclusion = (ListDictionary)concItem.Key;
                    string globalJoinType = (string)concItem.Value;

                    Dictionary<Dictionary<Attribute, Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool>>, string> MTLocalJoins =
                                                new Dictionary<Dictionary<Attribute, Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool>>, string>();
                       
                    foreach (DictionaryEntry dic in conclusion)
                    {
                        bool triggerBreak = false;
                        Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool> matchingTransmissions = null;
                        string attributeName = null;
                        string locJoinType = null;

                        ListDictionary entry = (ListDictionary)dic.Value;
                        foreach (DictionaryEntry locEntry in entry)
                        {
                            attributeName = (string)locEntry.Key;
                            locJoinType = (string)locEntry.Value;

                            Attribute attribute = MisUseAnObjectsDB.loadAttributeFull(attributeName, MainWindow.clusterName);

                            //matching transmission: sendReceiveContextAgent, bool:policy violated/not
                            matchingTransmissions = checkAttributePolicySatisfaction(sendAgent, receiveAgent, subjectAgent,
                                tokenisedAggregationThenContent, tokenisedContent, attribute, parameterisedContextInstances, sendReceiveContextAgent, contextInstance);

                            Dictionary<Attribute, Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool>> attMT =
                                new Dictionary<Attribute, Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool>>();
                            attMT.Add(attribute, matchingTransmissions);
                            
                            MTLocalJoins.Add(attMT, locJoinType);                                                

                            List<string> aggStatements = attribute.aggregation_statements;
                            if(aggStatements.Count>0)
                            {
                                foreach (string aggStatement in aggStatements)
                                {
                                    PolicyStatementAnalyser aggStatAnalyser = new PolicyStatementAnalyser();
                                    aggStatAnalyser.ifThenUnlessContentTokenisation(aggStatement);
                                    satisfiedAnalysis(sendAgent, receiveAgent, subjectAgent, aggStatAnalyser.tokenisedThenContent, tokenisedContent,
                                        aggStatement, parameterisedContextInstances, sendReceiveContextAgent, contextInstance);
                                }
                            }                            
                        }

                        foreach (KeyValuePair<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool> transmission in matchingTransmissions)
                        {
                            bool polSastisfied = transmission.Value;
                            if (polSastisfied == true && locJoinType.Equals("union"))
                            {
                                triggerBreak = true;
                                break;
                            }
                            else if (polSastisfied == false && locJoinType.Equals("intersection"))
                            {
                                triggerBreak = true;
                                break;
                            }
                        }

                        if (triggerBreak)
                        {
                            break;
                        }
                    }
                    MTGlobalJoins.Add(MTLocalJoins, globalJoinType);

                    foreach (KeyValuePair<Dictionary<Dictionary<Attribute, Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool>>, string>, string> MTGlobalJoin in MTGlobalJoins)
                    {
                        Dictionary<Dictionary<Attribute, Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool>>, string> MTLocalJoins_ = MTGlobalJoin.Key;
                        string aggStatement = MTGlobalJoin.Value;
                       
                        bool lastLocalEvaluation = false;
                        foreach (KeyValuePair<Dictionary<Attribute, Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool>>, string> MTLocalJoin in MTLocalJoins_)
                        {
                            Dictionary<Attribute, Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool>> attMT = MTLocalJoin.Key;
                            string localJoinType = MTLocalJoin.Value;

                            foreach (KeyValuePair<Attribute, Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool>> matchingTransSatisfactionYNAtt in attMT)
                            {
                                Attribute aggregatingAtt = matchingTransSatisfactionYNAtt.Key;
                                Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool> matchingTransSatisfactionYN = matchingTransSatisfactionYNAtt.Value;
                                                                
                                int fv = 0;
                                string lastJoin = "";
                                foreach (KeyValuePair<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool> transmission in matchingTransSatisfactionYN)
                                {
                                    bool polSastisfied = transmission.Value;
                                    if (fv == 0)
                                    {
                                        if (polSastisfied == true && localJoinType.Equals("union"))
                                        {
                                            lastLocalEvaluation = true;
                                            break;
                                        }
                                        else if (polSastisfied == false && localJoinType.Equals("union"))
                                        {
                                            lastLocalEvaluation = false;
                                        }
                                        else if (polSastisfied == false && localJoinType.Equals("intersection"))
                                        {
                                            lastLocalEvaluation = false;
                                            break;
                                        }
                                        else if (polSastisfied == true && localJoinType.Equals("intersection"))
                                        {
                                            lastLocalEvaluation = true;
                                        }
                                        lastJoin = localJoinType;
                                    }
                                    else
                                    {
                                        if (lastLocalEvaluation == true && lastJoin.Equals("union"))
                                        {
                                            break;
                                        }
                                        else if (lastLocalEvaluation == false && lastJoin.Equals("union"))
                                        {
                                            if (polSastisfied == true)
                                            {
                                                lastLocalEvaluation = true;
                                                break;
                                            }
                                            else if (polSastisfied == false)
                                            {
                                                lastLocalEvaluation = false;
                                            }
                                        }
                                        else if (lastLocalEvaluation == true && lastJoin.Equals("intersection"))
                                        {
                                            if (polSastisfied == true)
                                            {
                                                lastLocalEvaluation = true;
                                            }
                                            else if (polSastisfied == false)
                                            {
                                                lastLocalEvaluation = false;
                                            }
                                        }
                                        else if (lastLocalEvaluation == false && lastJoin.Equals("intersection"))
                                        {
                                            break;
                                        }
                                        lastJoin = localJoinType;
                                    }

                                    lastLocalEvaluation = transmission.Value;
                                    fv = fv + 1;
                                }
                            }
                        }
                        if (lastLocalEvaluation == true && globalJoinType.Equals("or"))
                        {
                            lastGlobalEvaluation = true;
                            globalTriggerBreak = true;
                            break;
                        }
                        else if (lastLocalEvaluation == false && globalJoinType.Equals("or"))
                        {
                            lastGlobalEvaluation = false;
                        }
                        else if (lastLocalEvaluation == true && globalJoinType.Equals("and"))
                        {
                            lastGlobalEvaluation = true;
                        }
                        else if (lastLocalEvaluation == false && globalJoinType.Equals("and"))
                        {
                            globalTriggerBreak = true;
                            lastGlobalEvaluation = false;
                            break;
                        }
                    }
                    
                }
                processedAggStatement.Add(MTGlobalJoins, aggregationStatement);

                if (globalTriggerBreak)
                {
                    break;
                }
            }
            processedAggregationStatements.Add(processedAggStatement, lastGlobalEvaluation);
        }

        private ListDictionary extractAttributeAndJoinsFromStatement(ListDictionary tokenisedAggregationThenContent, Context contextInstance)
        {
            //extract attributes and symbols from statement
            string aggTemporalConstraint = "";
            int aggNewKey = HistorySerialisationEngine.totalInteractions();

            ListDictionary premise = new ListDictionary();
            int preKey = 0;
            ListDictionary lastConclusion = new ListDictionary();
            ListDictionary conclusionList = new ListDictionary();

            int conKey = 0;
            bool entailsFound = false;
            string lastAttribute = "";
            string lastSymbol = "";
            string lastJoinOperator = "";

            foreach (DictionaryEntry aggItem in tokenisedAggregationThenContent)
            {
                int pol_id = (int)aggItem.Key;

                Dictionary<string, string> word_m = (Dictionary<string, string>)aggItem.Value;

                foreach (KeyValuePair<string, string> pair in word_m)
                {
                    string type = pair.Key;
                    string word = pair.Value;
                    if (type.Equals("temporalconstraint"))
                    {
                        aggTemporalConstraint = word;
                    }
                    else if (type.Equals("attribute"))
                    {
                        lastAttribute = word;
                        if (entailsFound == false && lastAttribute.Count() > 0)
                        {

                            premise.Add(preKey, word);
                            preKey = preKey + 1;
                        }
                    }
                    else if (type.Equals("entails"))
                    {
                        lastSymbol = word;
                        entailsFound = true;
                    }
                    else if (type.Equals("union"))
                    {
                        lastSymbol = word;
                        if (entailsFound && lastAttribute.Count() > 0)
                        {
                            ListDictionary entry = new ListDictionary();
                            entry.Add(lastAttribute, type);
                            lastConclusion.Add(conKey, entry);
                            conKey = conKey + 1;
                        }
                    }
                    else if (type.Equals("intersection"))
                    {
                        lastSymbol = word;
                        if (entailsFound && lastAttribute.Count() > 0)
                        {
                            ListDictionary entry = new ListDictionary();
                            entry.Add(lastAttribute, type);
                            lastConclusion.Add(conKey, entry);
                            conKey = conKey + 1;
                        }
                        //
                    }
                    else if (type.Equals("closingBracket"))
                    {
                        lastSymbol = word;
                        if (entailsFound && lastAttribute.Count() > 0)
                        {
                            ListDictionary entry = new ListDictionary();
                            entry.Add(lastAttribute, ")");
                            lastConclusion.Add(conKey, entry);
                            conKey = conKey + 1;
                        }
                        //
                    }

                    else if (type.Equals("and"))
                    {
                        lastJoinOperator = word;
                        if (entailsFound)
                        {
                            conclusionList.Add(lastConclusion, type);
                            lastConclusion = new ListDictionary();
                        }
                        //
                    }
                    else if (type.Equals("or"))
                    {
                        lastJoinOperator = word;
                        if (entailsFound)
                        {
                            conclusionList.Add(lastConclusion, type);
                            lastConclusion = new ListDictionary();
                        }
                        //
                    }
                    else if (type.Equals("openingBracket"))
                    {
                        //
                    }
                    else if (type.Equals("closingsquarebracket"))
                    {
                        //
                    }
                    else if (type.Equals("openingsquarebracket"))
                    {
                        //
                    }
                }
            }

            ListDictionary extracts = new ListDictionary();
            extracts.Add(premise, conclusionList);

            return extracts;
        }

        private static Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool> checkAttributePolicySatisfaction(Agent sendAgent, Agent receiveAgent, Agent subjectAgent,
                                           ListDictionary tokenisedAggregationThenContent, ListDictionary tokenisedContent, Attribute attribute,
                                            List<Object> parameterisedContextInstances, Dictionary<Dictionary<Agent, Agent>, ListDictionary> sendReceiveContextAgent, Context contextInstance )
        {
            ListDictionary aggContextItems = new ListDictionary();
            ListDictionary contextItems = new ListDictionary();
            string temporalConstraint = "";
            int newKey = HistorySerialisationEngine.totalInteractions();
            
            bool satisfiedThenSegment = false;

            Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool> matchingTransmissions = new Dictionary<Dictionary<Dictionary<Agent, Agent>, ListDictionary>, bool>();

            int i = 0;
            //foreach (KeyValuePair<List<Object>, Dictionary<Dictionary<Agent, Agent>, ListDictionary>> historyItem in Context.transmissionHistory)
            //{
            //    List<Object> parameterisedContextInstances = historyItem.Key;
            //    Dictionary<Dictionary<Agent, Agent>, ListDictionary> sendReceiveContextAgent = historyItem.Value;

            State message_s = null;
            Transition message_t = null;
            Agent h_sendAgent = null;
            Agent h_receiveAgent = null;
            Agent h_subjectAgent = null;

            foreach (KeyValuePair<Dictionary<Agent, Agent>, ListDictionary> pairx in sendReceiveContextAgent)
            {
                Dictionary<Agent, Agent> messageHeader = pairx.Key;
                foreach (KeyValuePair<Agent, Agent> sr in messageHeader)
                {
                    h_sendAgent = sr.Key;
                    h_receiveAgent = sr.Value;
                }

                ListDictionary messageBody = pairx.Value;
                foreach (DictionaryEntry mes in messageBody)
                {
                    h_subjectAgent = (Agent)mes.Key;
                    if (mes.Value is State)
                    {
                        message_s = (State)mes.Value;
                        message_t = null;
                    }
                    else if (mes.Value is Transition)
                    {
                        message_t = (Transition)mes.Value;
                        message_s = null;
                    }
                }
                    
                //if (sendAgent.agentName.Equals(h_sendAgent.agentName) &&
                //    receiveAgent.agentName.Equals(h_receiveAgent.agentName) &&
                //    subjectAgent.agentName.Equals(h_subjectAgent.agentName))
                if (subjectAgent.agentName.Equals(h_subjectAgent.agentName))
                {                        
                    bool attInMessage = false;
                    if (message_s != null)
                    {
                        Action activeAction = message_s.activeAction;
                        if (activeAction != null)
                        {
                            foreach (Attribute att in activeAction.parameterisedOperationalAttributes)
                            {
                                if (attribute.name.Equals(att.name))
                                {
                                    attInMessage = true;
                                    break;
                                }
                            }
                        }
                    }
                    else if (message_t != null)
                    {
                        Transition activeTransition = message_t;
                        if (activeTransition.activeEvent != null)
                        {
                            foreach (Attribute att in activeTransition.activeEvent.parameterisedOperationalAttributes)
                            {
                                if (attribute.name.Equals(att.name))
                                {
                                    attInMessage = true;
                                    break;
                                }
                            }
                        }
                    }

                    if (attInMessage == false)
                    {
                        continue;
                    }                       

                    bool attributeFunctionActive = false;
                    bool groupFunctionActive = false;

                    string lastEntity = "";
                    string lastEntityType = "";
                    string joinOperator = "";
                    string symbol = "";

                    foreach (DictionaryEntry policyItem in tokenisedContent)
                    {
                        int pol_id = (int)policyItem.Key;

                        Dictionary<string, string> word_m = (Dictionary<string, string>)policyItem.Value;

                        foreach (KeyValuePair<string, string> pair in word_m)
                        {
                            string type = pair.Key;
                            string word = pair.Value;
                            if (type.Equals("functionalAttribute"))
                            {
                                bool found = false;
                                if (message_s != null)
                                {
                                    if (message_s.name.Equals(word))
                                    {
                                        attributeFunctionActive = true;
                                        contextItems.Add(newKey, true);
                                        newKey = newKey + 1;
                                        found = true;
                                        lastEntity = word;
                                        lastEntityType = type;
                                    }
                                }
                                else if (message_t != null)
                                {
                                    string endState = message_t.endState;
                                    if (endState.Equals(word))
                                    {
                                        attributeFunctionActive = true;
                                        found = true;
                                        contextItems.Add(newKey, true);
                                        newKey = newKey + 1;
                                        lastEntity = word;
                                        lastEntityType = type;
                                    }
                                }

                                if (!found)
                                {
                                    contextItems.Add(pol_id, false);
                                }
                            }
                            else if (type.Equals("temporalconstraint"))
                            {
                                contextItems.Add(newKey, true);
                                temporalConstraint = word;
                                newKey = newKey + 1;
                            }
                            else if (type.Equals("attribute"))
                            {
                                bool found = false;
                                foreach (Object obj in parameterisedContextInstances)
                                {
                                    Attribute att = obj as Attribute;
                                    if (att != null)
                                    {
                                        if (att.name.Equals(word))
                                        {
                                            contextItems.Add(newKey, true);
                                            newKey = newKey + 1;
                                            found = true;
                                            lastEntity = word;
                                            lastEntityType = type;
                                            break;
                                        }
                                    }
                                }
                                if (!found)
                                {
                                    contextItems.Add(newKey, false);
                                    newKey = newKey + 1;
                                }
                            }
                            else if (type.Equals("number"))
                            {
                                double number;
                                if (Double.TryParse(word, out number))
                                {
                                    double word_val = Convert.ToDouble(word);

                                    if (lastEntityType.Equals("attribute"))
                                    {
                                        bool found = false;
                                        foreach (Object obj in parameterisedContextInstances)
                                        {
                                            Attribute att = obj as Attribute;
                                            if (att != null)
                                            {
                                                if (symbol.Equals("="))
                                                {
                                                    if (att.name.Equals(lastEntity))
                                                    {
                                                        if (Double.TryParse(att.activeDomain, out number))
                                                        {
                                                            double att_dom_val = Convert.ToDouble(att.activeDomain);
                                                            if (att_dom_val == word_val)
                                                            {
                                                                contextItems.Add(newKey, true);
                                                                newKey = newKey + 1;
                                                                found = true;
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                                else if (symbol.Equals("≠"))
                                                {
                                                    if (att.name.Equals(lastEntity))
                                                    {
                                                        if (Double.TryParse(att.activeDomain, out number))
                                                        {
                                                            double att_dom_val = Convert.ToDouble(att.activeDomain);
                                                            if (att_dom_val != word_val)
                                                            {
                                                                contextItems.Add(newKey, true);
                                                                newKey = newKey + 1;
                                                                found = true;
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                                else if (symbol.Equals("&lt;"))
                                                {
                                                    if (att.name.Equals(lastEntity))
                                                    {
                                                        if (Double.TryParse(att.activeDomain, out number))
                                                        {
                                                            double att_dom_val = Convert.ToDouble(att.activeDomain);
                                                            if (att_dom_val < word_val)
                                                            {
                                                                contextItems.Add(newKey, true);
                                                                newKey = newKey + 1;
                                                                found = true;
                                                                break;
                                                            }
                                                        }

                                                    }
                                                }
                                                else if (symbol.Equals(">"))
                                                {
                                                    if (att.name.Equals(lastEntity))
                                                    {
                                                        if (Double.TryParse(att.activeDomain, out number))
                                                        {
                                                            double att_dom_val = Convert.ToDouble(att.activeDomain);
                                                            if (att_dom_val > word_val)
                                                            {
                                                                contextItems.Add(newKey, true);
                                                                newKey = newKey + 1;
                                                                found = true;
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        if (!found)
                                        {
                                            contextItems.Add(newKey, false);
                                            newKey = newKey + 1;
                                        }
                                    }
                                }
                            }

                            else if (type.Equals("string"))
                            {
                                bool found = false;
                                if (lastEntityType.Equals("attribute"))
                                {
                                    foreach (Object obj in parameterisedContextInstances)
                                    {
                                        Attribute att = obj as Attribute;
                                        if (att != null)
                                        {
                                            if (symbol.Equals("="))
                                            {
                                                if (att.name.Equals(lastEntity))
                                                {
                                                    if (att.activeDomain.Equals(word))
                                                    {
                                                        contextItems.Add(newKey, true);
                                                        newKey = newKey + 1;
                                                        found = true;
                                                        break;
                                                    }
                                                }
                                            }
                                            else if (symbol.Equals("≠"))
                                            {
                                                if (att.name.Equals(lastEntity))
                                                {
                                                    if (!att.activeDomain.Equals(word))
                                                    {
                                                        contextItems.Add(newKey, true);
                                                        newKey = newKey + 1;
                                                        found = true;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                else if (lastEntityType.Equals("receiver"))
                                {
                                    foreach (Object obj in parameterisedContextInstances)
                                    {
                                        if (symbol.Equals("="))
                                        {
                                            if (receiveAgent.agentName.Equals(word))
                                            {
                                                contextItems.Add(newKey, true);
                                                newKey = newKey + 1;
                                                found = true;
                                                break;
                                            }
                                        }
                                        else if (symbol.Equals("≠"))
                                        {
                                            if (!receiveAgent.agentName.Equals(word))
                                            {
                                                contextItems.Add(newKey, true);
                                                newKey = newKey + 1;
                                                found = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                                else if (lastEntityType.Equals("sender"))
                                {
                                    foreach (Object obj in parameterisedContextInstances)
                                    {
                                        if (symbol.Equals("="))
                                        {
                                            if (sendAgent.agentName.Equals(word))
                                            {
                                                contextItems.Add(newKey, true);
                                                newKey = newKey + 1;
                                                found = true;
                                                break;
                                            }
                                        }
                                        else if (symbol.Equals("≠"))
                                        {
                                            if (!sendAgent.agentName.Equals(word))
                                            {
                                                contextItems.Add(newKey, true);
                                                newKey = newKey + 1;
                                                found = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                                else if (lastEntityType.Equals("subject"))
                                {
                                    foreach (Object obj in parameterisedContextInstances)
                                    {
                                        if (symbol.Equals("="))
                                        {
                                            if (subjectAgent.agentName.Equals(word))
                                            {
                                                contextItems.Add(newKey, true);
                                                newKey = newKey + 1;
                                                found = true;
                                                break;
                                            }
                                        }
                                        else if (symbol.Equals("≠"))
                                        {
                                            if (!subjectAgent.agentName.Equals(word))
                                            {
                                                contextItems.Add(newKey, true);
                                                newKey = newKey + 1;
                                                found = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                                if (!found)
                                {
                                    contextItems.Add(newKey, false);
                                    newKey = newKey + 1;
                                }
                            }
                            else if (type.Equals("and"))
                            {
                                contextItems.Add(newKey, true);
                                newKey = newKey + 1;
                                joinOperator = word;
                                aggContextItems.Add(contextItems, word);
                                contextItems = new ListDictionary();
                            }
                            else if (type.Equals("or"))
                            {
                                contextItems.Add(newKey, true);
                                newKey = newKey + 1;
                                joinOperator = word;
                                aggContextItems.Add(contextItems, word);
                                contextItems = new ListDictionary();
                            }
                            else if (type.Equals("sender"))
                            {
                                contextItems.Add(newKey, true);
                                newKey = newKey + 1;
                                lastEntityType = type;
                                lastEntity = word;
                            }
                            else if (type.Equals("lessthan") || type.Equals("greaterthan") || type.Equals("equals") || type.Equals("notequals"))
                            {
                                contextItems.Add(newKey, true);
                                newKey = newKey + 1;
                                symbol = word;
                            }
                            else if (type.Equals("receiver"))
                            {
                                contextItems.Add(newKey, true);
                                newKey = newKey + 1;
                                lastEntityType = type;
                                lastEntity = word;
                            }
                            else if (type.Equals("subject"))
                            {
                                contextItems.Add(newKey, true);
                                newKey = newKey + 1;
                                lastEntityType = type;
                                lastEntity = word;
                            }
                            else if (type.Equals("groupFunction"))
                            {
                                bool found = false;
                                foreach (Object obj in parameterisedContextInstances)
                                {
                                    GroupFunction gf = obj as GroupFunction;
                                    if (gf != null)
                                    {
                                        if (gf.functionName.Equals(word))
                                        {
                                            groupFunctionActive = true;
                                            contextItems.Add(newKey, true);
                                            newKey = newKey + 1;
                                            found = true;
                                            lastEntityType = type;
                                            lastEntity = word;
                                            break;
                                        }
                                    }
                                }
                                if (!found)
                                {
                                    contextItems.Add(newKey, false);
                                    newKey = newKey + 1;
                                }
                            }
                            else if (type.Equals("openingBracket"))
                            {
                                contextItems.Add(newKey, true);
                                newKey = newKey + 1;
                            }
                            else if (type.Equals("comma"))
                            {
                                contextItems.Add(newKey, true);
                                newKey = newKey + 1;
                            }
                            else if (type.Equals("closingBracket"))
                            {
                                if (attributeFunctionActive)
                                {
                                    attributeFunctionActive = false;
                                }
                                else if (groupFunctionActive)
                                {
                                    groupFunctionActive = false;
                                }

                                contextItems.Add(pol_id, true);
                            }
                            else if (type.Equals("closingsquarebracket"))
                            {
                                contextItems.Add(newKey, true);
                                newKey = newKey + 1;
                            }
                            else if (type.Equals("openingsquarebracket"))
                            {
                                contextItems.Add(newKey, true);
                                newKey = newKey + 1;
                            }
                        }
                    }

                    if (aggContextItems.Contains(contextItems))
                    {
                        ListDictionary dic = new ListDictionary();
                        foreach (DictionaryEntry pair in contextItems)
                        {
                            dic.Add(pair.Key, pair.Value);
                        }
                        aggContextItems.Add(dic, "NOJOIN");
                    }
                    else
                    {
                        aggContextItems.Add(contextItems, "NOJOIN");

                    }

                    foreach (DictionaryEntry contextItemkv in aggContextItems)
                    {
                        ListDictionary contextItem = (ListDictionary)contextItemkv.Key;
                        string jointype = (string)contextItemkv.Value;
                        bool fault = false;
                        foreach (DictionaryEntry item in contextItem)
                        {
                            bool val = (bool)item.Value;
                            if (val == false)
                            {
                                fault = true;
                            }
                        }

                        if (fault == false)
                        {
                            satisfiedThenSegment = true;
                        }
                        else
                        {
                            satisfiedThenSegment = false;
                        }
                        if (jointype.Equals("∧") && satisfiedThenSegment == false)
                        {
                            break;
                        }
                        else if (jointype.Equals("∧") && satisfiedThenSegment == true)
                        {
                            //continue;
                        }
                        else if (jointype.Equals("V") && satisfiedThenSegment == true)
                        {
                            break;
                        }
                        else if (jointype.Equals("V") && satisfiedThenSegment == false)
                        {
                            //continue;
                        }
                    }

                    matchingTransmissions.Add(sendReceiveContextAgent, satisfiedThenSegment);

                }

                //if (satisfiedThenSegment == true)
                //{
                //    break;
                //}
                //else
                //{
                //    aggContextItems = new ListDictionary();
                //}
            }
            //}

            return matchingTransmissions;
        }
    }
}



